package com.emm.yixun.system.service.impl.manage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.DistributionService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.MsgSettingService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Distribution;
import com.emm.yixun.common.model.MsgSetting;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.DistributionDto;
import com.emm.yixun.common.model.dto.MsgSettingDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.enums.IsValidEnum;
import com.emm.yixun.common.model.enums.TempTypeEnum;
import com.emm.yixun.common.utils.MsgUtil;

@Service("customerManageNoticeManage")
public class CustomerManageNoticeManage {

	@Autowired
	private NoticeService noticeService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private MsgSettingService msgSettingService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysNoticeManage sysNoticeManage;
	@Autowired
	private ProjectSettingService projectSettingService;
	
	/**
	 * 插入消息
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO createNotice() {
		CommonResDTO resDto = new CommonResDTO();
		resDto.setResult("0");
		try{
			//1、根据sys_tm_msg_setting设置,获取消息提醒时间
	    	//获取客户维护消息设置
			MsgSettingDto settingDto = new MsgSettingDto();
			settingDto.setTempType(TempTypeEnum.RE04.getNo());
			List<MsgSetting> settingList = msgSettingService.selectListByDto(settingDto);
			if(settingList != null){
				//跟进提醒（客户未跟进提醒模板 NT03【经纪人】）
				String msgTemp = "你的客户${customer}未跟进,将会被分配给其他置业顾问。";
				//超时未跟进提醒（客户超时未跟进提醒模板 NT05【经纪人、销管负责人】）
				String msgTemp_2 = "经纪人${agent}已有${day}天未跟进${customer}客户。";
				String sendMsg = "";
	 			DictionaryDto dicDto = new DictionaryDto();
 				dicDto.setDictionaryType("NT");
 				List<Dictionary> dicList = dictionaryService.selectListByDto(dicDto);
 				if(dicList != null){
 					for(Dictionary dic: dicList){
 	 					if("NT03".equals(dic.getDictionaryValue())){
 	 						msgTemp = dic.getDictionaryName();
 	 					}else if("NT05".equals(dic.getDictionaryValue())){
 	 						msgTemp_2 = dic.getDictionaryName();
 	 					}
 	 				}
 				}
	 			//遍历商户客户维护消息设置
	 			for(MsgSetting setting: settingList){
	 				//2、查询客户表[cus_tm_customer]中最后跟进时间[last_follow_time]
	 				//跟当天比较,时间差>=模板表中的触发时间[attack_time]天
	 				//统计日期+1,超过设置的跟进日期即可进行统计发送提醒
	 				int attackTime = setting.getAttackTime() + 1;
			 		Calendar calendar = Calendar.getInstance();
			 		calendar.add(Calendar.DAY_OF_MONTH, (attackTime * (-1)));
			 		String followTimeBefore = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH)+1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " 00:00:00";
			 		String followTimeAfter = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH)+1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " 23:59:59";
			 		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 		CustomerDto customerDto = new CustomerDto();
			 		customerDto.setMerchantId(setting.getMerchantId());
			 		customerDto.setLastFollowTimeBefore(sdf.parse(followTimeBefore));
			 		customerDto.setLastFollowTimeAfter(sdf.parse(followTimeAfter));
			 		//超时未跟进的客户(超过未跟进警告期限)
			 		List<Customer> customerList = customerService.selectListByDto(customerDto);
			 		if(customerList != null){
			 			for(Customer customer: customerList){
			 				sendMsg = msgTemp.replace("${customer}", customer.getCustomerName());
			 				Map<String, String> noticeParamMap = new HashMap<String, String>();
							noticeParamMap.put("noticeDicId", "162");
							noticeParamMap.put("noticeTempType", "NT03");
							noticeParamMap.put("sendMsg", sendMsg);
							noticeParamMap.put("title", "客户维护,未跟进提醒");
							noticeParamMap.put("merchantId", String.valueOf(customer.getMerchantId()));
							noticeParamMap.put("projectCode", customer.getProjectCode());
							noticeParamMap.put("userCode", customer.getUserCode());
							noticeParamMap.put("accessCode", customer.getAccessCode());
							noticeParamMap.put("createUserId", String.valueOf(customer.getCreateUserId()));
							
							/*
							 * (ym) 提醒内容增加超链接 start
							 * */
							Map<String,String> replaceValuesMap=new HashMap<String,String>();
							replaceValuesMap.put(MsgUtil.ROOM_ID, "");
							replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
							replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
							replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
							replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
					    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
					    	/*
							 * (ym) 提醒内容增加超链接 end
							 * */
							
							//查询客户经纪人
							List<User> userList = new ArrayList<User>();
							DistributionDto distDto = new DistributionDto();
							distDto.setCustomerId(customer.getId());
							distDto.setIsValid(IsValidEnum.VALID.getNo());
							Distribution dist = distributionService.selectByDto(distDto);
							User user = null;
							if(dist != null){
								user = userService.selectById(Long.parseLong(dist.getAssignPerson()));
								userList.add(user);
							}
							sysNoticeManage.createNotice(noticeParamMap, userList);
				 		}
			 		}
			 		
			 		//3、查询客户表[cus_tm_customer]中最后跟进时间[last_follow_time]
	 				//跟当天比较,时间差>=模板表中的触发时间[limit_days]天
	 				//统计日期+1,超过设置的跟进日期即可进行统计发送提醒
			 		//查询超过最大未跟进日期的客户,提醒用户,客户将会被重新分配
		 			int limitDays = setting.getLimitDays() + 1;
			 		calendar = Calendar.getInstance();
			 		calendar.add(Calendar.DAY_OF_MONTH, (limitDays * (-1)));
			 		followTimeBefore = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH)+1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " 00:00:00";
			 		followTimeAfter = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH)+1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + " 23:59:59";
			 		customerDto = new CustomerDto();
			 		customerDto.setMerchantId(setting.getMerchantId());
			 		customerDto.setLastFollowTimeBefore(sdf.parse(followTimeBefore));
			 		customerDto.setLastFollowTimeAfter(sdf.parse(followTimeAfter));
			 		//超时未跟进的客户(超过最大未跟进期限)
			 		customerList = customerService.selectListByDto(customerDto);
			 		if(customerList != null){
				 		for(Customer customer_2: customerList){
			 				//查询客户经纪人
							List<User> userList = new ArrayList<User>();
							DistributionDto distDto = new DistributionDto();
							distDto.setCustomerId(customer_2.getId());
							distDto.setIsValid(IsValidEnum.VALID.getNo());
							Distribution dist = distributionService.selectByDto(distDto);
							User user = null;
							String userName = "";
							if(dist != null){
								user = userService.selectById(Long.parseLong(dist.getAssignPerson()));
								userList.add(user);
								userName = user.getUserName();
							}
							//查询销管负责人
							ProjectSettingDto entity_proSetting = new ProjectSettingDto();
							entity_proSetting.setProjectCode(customer_2.getProjectCode());
							ProjectSetting projectSetting = projectSettingService.selectByDto(entity_proSetting);
							if(projectSetting != null){
								user = userService.selectById(projectSetting.getMaLeader());
								userList.add(user);
							}
			 				
			 				sendMsg = msgTemp_2.replace("${agent}", userName).replace("${day}",String.valueOf(attackTime)).replace("${customer}",customer_2.getCustomerName());
			 				Map<String, String> noticeParamMap = new HashMap<String, String>();
							noticeParamMap.put("noticeDicId", "164");
							noticeParamMap.put("noticeTempType", "NT05");
							noticeParamMap.put("sendMsg", sendMsg);
							noticeParamMap.put("title", "客户维护,超时未跟进提醒");
							noticeParamMap.put("merchantId", String.valueOf(customer_2.getMerchantId()));
							noticeParamMap.put("projectCode", customer_2.getProjectCode());
							noticeParamMap.put("userCode", customer_2.getUserCode());
							noticeParamMap.put("accessCode", customer_2.getAccessCode());
							noticeParamMap.put("createUserId", String.valueOf(customer_2.getCreateUserId()));
							
							sysNoticeManage.createNotice(noticeParamMap, userList);
				 		}
			 		}
	 			}
	 			resDto.setResult("1");
			}
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("添加提醒消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	
}
